package com.h3bpm.web.engineEvent;


import OThinker.Common.Data.Database.ICommand;
import OThinker.Common.DateTimeUtil;
import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.Common.Organization.Models.User;
import OThinker.EngineConfigUtil;
import OThinker.H3.Controller.AppCode.Admin.ConstantString;
import OThinker.H3.Entity.IEngine;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.WorkItem.CirculateModels.CirculateItem;
import OThinker.H3.Entity.WorkItem.CirculateModels.CirculateItemFinished;
import OThinker.H3.Entity.WorkItem.WorkItemModels.WorkItem;
import OThinker.H3.Entity.WorkItem.WorkItemModels.WorkItemFinished;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import data.DataColumn;
import data.DataColumnCollection;
import data.DataTable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class MessageHelper {

    private static final Logger logger = LoggerFactory.getLogger(MessageHelper.class);

    /**
     *  系统 Restful 接口地址
     */
    private static String msgRestUrl = "http://127.0.0.1/";

    /**
     * H3BPM 系统的PC端URL地址
     */
    private static String h3bpmPcUrl = "http://10.50.132.106/";

    /**
     * http连接超时设置,默认0
     */
    private static int time_out = 0;

    private static String systemCode;
    private static String secret;



    static {
        String value = null;
        value = EngineConfigUtil.getSystemProperty("message.msgRestUrl");
        if(StringUtils.isNotBlank(value)){ msgRestUrl = value;}

        value = EngineConfigUtil.getSystemProperty("message.h3bpmPcUrl");
        if(StringUtils.isNotBlank(value) && !value.endsWith("/")){

            value = value + "/";
        }
        if(StringUtils.isNotBlank(value)) {
            h3bpmPcUrl = value;
        }

        value = EngineConfigUtil.getSystemProperty("message.systemCode");
        if(StringUtils.isNotBlank(value)){
            systemCode = value;
        }
        value = EngineConfigUtil.getSystemProperty("message.secret");
        if(StringUtils.isNotBlank(value)){
            secret = value;
        }


        System.out.println("cccg h3bpm pc url=" + msgRestUrl);
        System.out.println("cccg h3bpm pc url=" + h3bpmPcUrl);
    }




    /**
     *
     * 待办待阅任务 生成发送待办的JSON内容
     *
     * @param engine
     * @param workItem
     * @return
     * @throws Exception
     */
    public static String createRequestByWorkItem(IEngine engine, WorkItem workItem,CirculateItem circulateItem,String method) throws Exception {
        logger.info("进入待办待阅的createRequestByWorkItem方法");
        InstanceContext instanceContext = null;
        //发起人user
        User user = null;
        //获取接收人部门
        //接收人user
        User receiveUser = null;
        OrganizationUnit organizationUnit = null;
        if(workItem == null){

            instanceContext = engine.getInstanceManager().GetInstanceContext(circulateItem.getInstanceID());
            user = (User) engine.getOrganization().GetUnit(circulateItem.getOriginator());
            receiveUser = (User) engine.getOrganization().GetUnit(circulateItem.getParticipant());
            organizationUnit = (OrganizationUnit) engine.getOrganization().GetUnit(receiveUser.getParentID());

        }else{

            instanceContext = engine.getInstanceManager().GetInstanceContext(workItem.getInstanceID());
            user = (User) engine.getOrganization().GetUnit(workItem.getOriginator());
            receiveUser = (User) engine.getOrganization().GetUnit(workItem.getParticipant());
            organizationUnit = (OrganizationUnit) engine.getOrganization().GetUnit(receiveUser.getParentID());

        }

        JSONObject map = new JSONObject();
//        Map<String,Object> map = new HashMap<>();
        String header = "请审批：关于" + user.getName() + "发起的" + instanceContext.getInstanceName() + "的待办";
        String sequenceNo = instanceContext.getSequenceNo();
        String node = "";
        String initiationTime = DateTimeUtil.format(instanceContext.getCreatedTime());

        //查询后台	OT_Attachment  判断流程中是否存在附件
        ICommand command = engine.getEngineConfig().getCommandFactory().CreateCommand();
        String bizObjectId = instanceContext.getBizObjectId();
        String querySql = "select fileName as filedName,objectId as filedUrl from ot_Attachment where bizObjectId ='"+bizObjectId+"'";
        DataTable dataTable = command.ExecuteDataTable(querySql);
        logger.info("打印查询附件数量的语句：{}",querySql);
//        ArrayList<Object> attaList = new ArrayList<>();
        JSONArray attaList = new JSONArray();
        if(dataTable != null){
            List<Map<String, String>> rowList = getRowList(dataTable);
            for (int i = 0; i < rowList.size(); i++) {
                Map<String, String> rowMap = rowList.get(i);
                String AttachmentID = rowMap.get("filedUrl");
                String s = "/Portal/ReadAttachment/Read?AttachmentID=" + AttachmentID;
                rowMap.put("filedUrl",s);
                attaList.add(rowMap);

            }

            logger.info("附件的JOSN数组：{}",attaList);

        }

        String name = "";
        String businessId = "";
        String title = "";
        Date createTime = null;
        String promoter = "";
        String promoterOrg = "";
        String receiverUserCode = "";
        if(circulateItem == null){
            if("OnUpdated".equals(method)){
                name = "[催办]" + header;
            }else {
                name = "[待办]" + header;
            }
            businessId = workItem.getObjectID();
            title = workItem.getDisplayName();
            createTime = workItem.getReceiveTime();
            //发起人
            promoter = user.getCode();
            promoterOrg = organizationUnit.getName();
            //接收人
            receiverUserCode = receiveUser.getCode();
            //当前节点名称
            node = workItem.getDisplayName();
        }else{

            name = "[抄送]'" + header + "'抄送给您，请查阅！";
            businessId = circulateItem.getObjectID();
            title = circulateItem.getDisplayName();
            createTime = circulateItem.getReceiveTime();
            //发起人
            promoter = user.getCode();
            promoterOrg = organizationUnit.getName();
            //接收人
            receiverUserCode = receiveUser.getCode();
            //当前节点名称
            node = circulateItem.getDisplayName();
        }

        String pcUrl = "Portal/WorkItemSheets.html?WorkItemID=" + businessId;

        //创建时间的时间戳
        map.put("createTime",createTime);
        //发起人
        map.put("promoter",promoter);
        //发起部门
        map.put("promoterOrg",promoterOrg);
        //当前节点名称
        map.put("node",node);
        //接收人user
        map.put("userAccountList",receiverUserCode);
        // 消息标题
        map.put("title",title);
        // 消息内容
        map.put("content",name);
        // sequenceNo
        map.put("sequenceNo",sequenceNo);
        // 创建时间点
        map.put("initiationTime",initiationTime);
        // pc端的流程地址，不含ip和端口号
        map.put("pcUrl",pcUrl);

        String url = msgRestUrl + "Portal/MessageCenterController/addMsg";
        String appUrl = msgRestUrl + "Portal/MessageCenterController/appAddMsg";
        logger.info("<><><> bpm addMsg portal推送消息接口：{}：<><><>", url);
        logger.info("<><><> addMsg 参数封装完成: {}： <><><>", map.toJSONString());
        String result;
        try {
            result = HttpLocalUtils.doPost(appUrl,map.toJSONString());
            logger.info("<><><> appAddMsg bpm推送消息：{}：<><><>",map);
            if(StringUtils.isNotBlank(result)){
                JSONObject resBodyDto = JSON.parseObject(result);
                if(resBodyDto.getInteger("errcode") == 0L){
                    logger.info("<><><> appAddMsg bpm推送消息成功：{}：<><><>",map);
                }
            }else{
                logger.info("<><><> addMsg bpm推送消息失败：{}： <><><>",map);
            }
        }catch (Exception e){
            logger.info(e.getMessage());
        }

        try {
            result = HttpLocalUtils.doPost(url,map.toJSONString());
            if(StringUtils.isNotBlank(result)){
                JSONObject resBodyDto = JSON.parseObject(result);
                if(resBodyDto.getInteger("errcode") == 0L){
                    logger.info("<><><> addMsg bpm推送消息成功：{}：<><><>",map);
                }
            }else{
                logger.info("<><><> addMsg bpm推送消息失败：{}： <><><>",map);
            }
        }catch (Exception e){
            logger.info(e.getMessage());
        }

        return "success";
    }


    /**
     * 已办已阅参数传递
     * @param engine
     * @param circulateItemFinished
     * @param workItemFinished
     * @return
     * @throws Exception
     */
    public static String createRequestByCirculate(IEngine engine, CirculateItemFinished circulateItemFinished, WorkItemFinished workItemFinished) throws Exception {

        //接收人user
        User receiveUser = null;
        if(circulateItemFinished == null){
            receiveUser = (User) engine.getOrganization().GetUnit(workItemFinished.getParticipant());

        }else{
            receiveUser = (User) engine.getOrganization().GetUnit(circulateItemFinished.getParticipant());
        }

        logger.info("<<<>>>执行修改流程状态》》》》》");

        String businessId = "";
        String receiverUserCode = "";
        String completeTime = "";
        Integer status = null;
        if(workItemFinished == null){
             businessId = circulateItemFinished.getObjectID();
             receiverUserCode = receiveUser.getCode();
             completeTime = DateTimeUtil.format(circulateItemFinished.getFinishTime());
             status = 1;
            logger.info("<><>circulateItemFinished修改已阅参数完成：{}",businessId);
        }else{
            businessId = workItemFinished.getObjectID();
            receiverUserCode = receiveUser.getCode();
            completeTime = DateTimeUtil.format(workItemFinished.getFinishTime());
            status = 1;
            logger.info("<><>workItemFinished修改已办参数完成：{}",businessId);
        }

        JSONObject map = new JSONObject();
        map.put("businessId",businessId);
        map.put("receiverUserCode",receiverUserCode);
        map.put("completeTime",completeTime);
        map.put("status",status);
        map.put("systemCode",systemCode);
        map.put("secret",secret);
        logger.info("<><><> updateMsg 的参数已封装完成：{}  <><><>",map.toJSONString());
        String url = msgRestUrl + "Portal/MessageCenterController/updateMsg";
        logger.info("<><><>bpm updateMsg portal推送消息接口：{}  <><><>", url);

        Map<String, String> headersMap = new HashMap<String, String>();
        headersMap.put("Content-Type","application/json; charset=utf-8");
        String result = HttpLocalUtils.doPost(url,map.toString());

        if(StringUtils.isNotBlank(result)){
            JSONObject resBodyDto = JSON.parseObject(result);
            logger.info("<><><>updateMsg的参数，返回结果集参数：{}  <><><> ",resBodyDto.toJSONString());
            if(resBodyDto.getInteger("errcode") == 0L){
                logger.info("<><><>updateMsg消息响应成功：{} <><><>",map);
            }

        }else{
            logger.info("<><><>updateMsg消息响应失败：{}  <><><>",map);
        }

        return result;
    }


    /**
     * 获取表单数据
     *
     * @param dataTable
     *            表单
     * @return json
     * @throws Exception
     */
    private static List<Map<String, String>> getRowList(DataTable dataTable) throws Exception {
        List<Map<String, String>> rowList = new ArrayList<Map<String, String>>();
        if (dataTable != null) {
            Map<String, String> columnDictionary = new LinkedHashMap<String, String>();
            DataColumnCollection columns = dataTable.getColumns();
            for (int i = 0; i < columns.size(); i++) {
                DataColumn c = columns.get(i);
                if (!columnDictionary.containsKey(c.getColumnName())) {
                    columnDictionary.put("".equals(c.getColumnName()) ? ConstantString.DefaultName : c.getColumnName(),
                            "");
                }
            }

            if (dataTable.getRows().size() > 0) {
                for (int i = 0; i < dataTable.getRows().size(); i++) {
                    Map<String, String> temp = new LinkedHashMap<String, String>();
                    for (String key : columnDictionary.keySet()) {
                        temp.put(key, dataTable.getRows().get(i).getObject(key) != null
                                ? dataTable.getRows().get(i).getObject(key).toString() : "");
                    }
                    rowList.add(temp);
                }
            }
        }
        return rowList;
    }


}
